package com.miao.edu.user.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.miao.edu.common.entity.ResponseDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <p>
 *     根据用户登录时提供的信息，生成token返回给用户
 * </p>
 *
 * @author niemiao
 */
@Slf4j
@Service
public class UserService {

    @Autowired
    private UserOauthRemoteService userOauthRemoteService;

    @Value("${spring.oauth.client_id}")
    private String clientId;
    @Value("${spring.oauth.client_secret}")
    private String clientSecret;
    @Value("${spring.oauth.scope}")
    private String scope;
    @Value("${spring.oauth.grant_type}")
    private String grantType;
    @Value("${spring.oauth.refresh_grant_type}")
    private String refreshGrantType;


    public ResponseDTO<String> createAuthToken(String phone, String password, String code, int loginType) {

        log.info("phone:{}, password:{}, scope:{}, grantType:{}, clientId:{}, clientSecret:{}", phone, password, scope, grantType, clientId, clientSecret);
        String token = null;

        // 判断登录类型，采取不同的验证方式
        try {
            // 0 等于密码登录方式，这也是默认的登录方式
            if (0 == loginType) {
                token = this.userOauthRemoteService.createToken(phone, password, scope, grantType, clientId, clientSecret, null);
                // 1 等于手机验证码登录的方式
            } else if (1 == loginType) {
                token = this.userOauthRemoteService.createToken(phone, code, scope, grantType, clientId, clientSecret, "mobile");
            } // ToDo 微信登录方式

            if (StringUtils.isBlank(token)) {
                return ResponseDTO.response(206,"登录失败");
            }
            JSONObject jsonObject = JSON.parseObject(token);
            String resultCode = jsonObject.getString("code");

            // 当返回 resultCode 时表示登录失败
            if (StringUtils.isNotBlank(resultCode)) {
                // 判断是否是验证码错误
                if ("040072".equals(resultCode)) {
                    return ResponseDTO.ofError(207, "验证码错误(" + resultCode + ")");
                }
                return ResponseDTO.response(206,"登录失败");
            }
            // 判断是否返回了 userId，以此来判断是否成功生成token
            String userId = (String)jsonObject.get("user_id");
            if (StringUtils.isBlank(userId)) {
                return ResponseDTO.response(-1,"登录失败");
            }
            return ResponseDTO.response(1,"success",token);

        }catch (Exception e) {
            System.out.println(e.getMessage());
            return ResponseDTO.ofError("登录失败");
        }

    }
}
